package com.house365.updown.download;

import java.util.LinkedList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.house365.core.util.TextUtil;
import com.house365.core.util.db.DataBaseOpenHelper;
import com.house365.core.util.db.DataBaseOpenHelper.DataBaseOpenListener;
import com.house365.core.util.db.DataBaseService;
import com.house365.core.util.db.DataBaseService.DBQuery;

/**
 * @author py
 * @date 2013-5-22
 * @comment
 */
public class DownloaderDBService {
	// public static final int STATUS_PENDING = 1;
	// public static final int STATUS_RUNNING = 2;
	// public static final int STATUS_PAUSED = 4;
	// public static final int STATUS_SUCCESSFUL = 8;
	// public static final int STATUS_FAILED = 16;
	private DataBaseService dbService;
	private static DownloaderDBService instance;

	public DownloaderDBService(Context context) {
		dbService = new DataBaseService(context, "downloader", 1,
				new DataBaseOpenListener() {

					@Override
					public void onVersionUpgrade(SQLiteDatabase db, int arg1,
							int arg2) {
						// TODO Auto-generated method stub

					}

					@Override
					public String[] getIndexSql() {
						String[] indexsqlArray = {
								"CREATE INDEX [IDX_DFILE_OUTERID] ON [dfile]([outerid]  ASC)",
								"CREATE INDEX [IDX_DFILE_REFERID] ON [dfile]([referId]  ASC)" };
						return indexsqlArray;
					}

					@Override
					public String[] getCreateSql() {
						return new String[]{"CREATE TABLE IF NOT EXISTS dfile (identity integer primary key autoincrement,outerid varchar(100),referId long, remoteFileUri varchar(100),totalSize long, downSize long,status int,reason int,"
								+ "localFileUri varchar(100),type int)"};
					}
				});
	}

	public static DownloaderDBService getDBService(Context context) {
		if (instance == null)
			instance = new DownloaderDBService(context);
		return instance;
	}

	public LinkedList<DFile> getDFiles(int type) {
		return (LinkedList<DFile>) dbService.query(
				"select * from dfile where type = " + type, null,
				new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						LinkedList<DFile> dfiles = new LinkedList<DFile>();
						while (cursor.moveToNext()) {
							DFile dfile = new DFile();
							dfile.readFromCursor(cursor);
							dfiles.add(dfile);
						}
						return dfiles;
					}
				});
	}

	public void saveDFiles(int type, LinkedList<DFile> datas) {
		try {
			DataBaseOpenHelper dbo = dbService.getDbOpenHelper();
			SQLiteDatabase db = dbo.getWritableDatabase();
			db.beginTransaction();
			for (DFile dfile : datas) {
				db.execSQL(
						"insert into dfile(outerid,referId, remoteFileUri,totalSize,status,reason,localFileUri,type)values(?,?,?,?,?,?,?,?)",
						new Object[] { TextUtil.getUTF8(dfile.getOuterid()),
								dfile.getReferId(),
								TextUtil.getUTF8(dfile.getRemoteFileUri()),
								dfile.getTotalSize(), dfile.getStatus(),
								dfile.getReason(),
								TextUtil.getUTF8(dfile.getLocalFileUri()), type });
			}
			db.setTransactionSuccessful();
			db.endTransaction();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void saveDFile(DFile dfile, int type) {
		dbService
				.execute(
						"insert into dfile(outerid,referId, remoteFileUri,totalSize,status,reason,localFileUri,type)values(?,?,?,?,?,?,?,?)",
						new Object[] { TextUtil.getUTF8(dfile.getOuterid()),
								dfile.getReferId(),
								TextUtil.getUTF8(dfile.getRemoteFileUri()),
								dfile.getTotalSize(), dfile.getStatus(),
								dfile.getReason(),
								TextUtil.getUTF8(dfile.getLocalFileUri()), type });
	}

	public void removeDFileByReferId(long referid) {
		dbService.execute("delete from  dfile where referId  =  " + referid
				, new Object[] {});
	}

	public void removeDFileOuterId(String outerid) {
		dbService.execute("delete from  dfile where outerid  =  " + outerid
				, new Object[] {});
	}

	public DFile getDFileByReferId(long referid) {
		return (DFile) dbService.query("select * from dfile where referId = ?",
				new String[] { referid + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						DFile dfile = null;
						if (cursor.moveToNext()) {
							dfile = new DFile();
							dfile.readFromCursor(cursor);
						}
						return dfile;
					}
				});
	}

	public DFile getDFileByOuterId(String outerid) {
		return (DFile) dbService.query("select * from dfile where outerid = ?",
				new String[] { outerid }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						DFile dfile = null;
						if (cursor.moveToNext()) {
							dfile = new DFile();
							dfile.readFromCursor(cursor);
						}
						return dfile;
					}
				});
	}

	public DFile getFirstQueueDFile() {
		return (DFile) dbService.query(
				"select * from dfile where type = ? order by identity ",
				new String[] { Downloader.DOWN_STAUTS_QUEUE + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						DFile dfile = null;
						if (cursor.moveToNext()) {
							dfile = new DFile();
							dfile.readFromCursor(cursor);
						}
						return dfile;
					}
				});
	}
	public DFile getDownloadingDFile() {
		return (DFile) dbService.query(
				"select * from dfile where type = ? order by identity ",
				new String[] { Downloader.DOWN_STAUTS_DOWNING + "" }, new DBQuery() {

					@Override
					public Object onQueryResult(Cursor cursor) {
						DFile dfile = null;
						if (cursor.moveToNext()) {
							dfile = new DFile();
							dfile.readFromCursor(cursor);
						}
						return dfile;
					}
				});
	}
	public void moveDonwloadingToQueue(DFile dfile){
		dbService
		.execute(
				"update  dfile set type = ?,totalSize =0,downSize=0 where identity = ?",
				new Object[] { Downloader.DOWN_STAUTS_DOWNED,dfile.getIdentity()});
	}
	public void moveQueueToDonwloading(DFile dfile){
		dbService
		.execute(
				"update  dfile set type = ?,referId=? where identity = ?",
				new Object[] { Downloader.DOWN_STAUTS_DOWNING,dfile.getReferId(),dfile.getIdentity()});
	}
	public void moveDonwloadingToDownloaded(DFile dfile){
		dbService
		.execute(
				"update  dfile set type = ?,totalSize =?,downSize=?,status = ?,reason = ?,localFileUri = ? where identity = ?",
				new Object[] { Downloader.DOWN_STAUTS_DOWNED,dfile.getTotalSize(),dfile.getDownSize(),dfile.getStatus(),dfile.getReason(),TextUtil.getUTF8(dfile.getLocalFileUri()),dfile.getIdentity()});
	}
	public void updateDownloadingInfo(DFile dfile){
		dbService
		.execute(
				"update  dfile set totalSize =?,downSize=?,status = ?,reason = ? where identity = ?",
				new Object[] { dfile.getTotalSize(),dfile.getDownSize(),dfile.getStatus(),dfile.getReason(),dfile.getIdentity()});
	}
	
	public void clear(){
		dbService
		.execute("delete from dfile",new Object[]{});
	}
}
